<template>
  <div>
    <!-- 导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区 -->
    <el-card class="box-card">
      <el-row :gutter="30">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getuserlist">
            <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户数据区 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatechanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="small"
                @click="showedituser(scope.row.id)"
              ></el-button>
              <!-- 删除按钮 -->

              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="small"
                @click="deleteuser(scope.row.id)"
              ></el-button>

              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  circle
                  size="small"
                  @click="Assignpermissions(scope.row)"
                ></el-button>
              </el-tooltip>
              <!-- 分配角色按钮 -->
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="formclosed">
      <!-- 内容主体 -->

      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- <el-form-item label="角色" prop="role">
          <el-input v-model="addForm.role"></el-input>
        </el-form-item>-->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submituser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editformclosed">
      <!-- 内容主体 -->

      <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edituser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setdialogVisible" width="50%" @close="setdialogclosed">
      <div>
        <p>当前用户：{{userinfo.username}}</p>
        <p>当前角色：{{userinfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saverolesinfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //验证邮箱自定义规则
    var checkEmail = (rule, value, cb) => {
      //  验证邮箱的正则表达式
      const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号自定义规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^0{0,1}(13[4-9]|15[7-9]|15[0-2]|18[7-8])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表的参数对象
      queryinfo: {
        query: "",
        //当前页数
        pagenum: 1,
        //每页显示条数
        pagesize: 2,
      },
      userlist: [],
      // 所有数据的角色列表
      rolesList: [],
      // 需要被分配角色的用户信息
      userinfo: {},
      // 已选中得角色id值
      selectRoleId: "",
      total: 0,
      //控制对话框显示
      addDialogVisible: false,
      // 修改对话框显示
      editDialogVisible: false,
      // 分配对话框显示
      setdialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        // role:""
      },
      // 修改用户数据
      editForm: {},
      //添加表单验证规则对象
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        // role: [
        //   { required: true, message: "请输入角色", trigger: "blur" },
        //   {
        //     min: 2,
        //     max: 8,
        //     message: "长度在 2 到 8 个字符",
        //     trigger: "blur",
        //   },
        // ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //修改表单验证规则对象
      editFormrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    async getuserlist() {
      const { data: res } = await this.$axios.get("users", {
        params: this.queryinfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("用户列表获取失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //信息条数改变事件
    handleSizeChange(newSize) {
      this.queryinfo.pagesize = newSize;
      this.getuserlist();
    },
    //换页事件
    handleCurrentChange(newPage) {
      this.queryinfo.pagenum = newPage;
      this.getuserlist();
    },
    //用户状态监听
    async userStatechanged(userinfo) {
      const { data: res } = await this.$axios.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("状态更新失败");
      }
      this.$message.success("用户状态更改成功");
    },
    //监听添加用户框的关闭
    formclosed() {
      this.$refs.addFormRef.resetFields();
    },
    //监听修改用户框的关闭
    editformclosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 提交用户请求
    submituser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          // 发起请求
          const { data: res } = await this.$axios.post("users", this.addForm);
          if (res.meta.status !== 201)
            return this.$message.error("用户添加失败");
          this.$message.success("用户添加成功");
          //添加用户框关闭
          this.addDialogVisible = false;
          this.getuserlist();
        } else {
          return false;
        }
      });
    },
    //展示修改编辑对话框
    async showedituser(id) {
      this.editDialogVisible = !this.editDialogVisible;
      const { data: res } = await this.$axios.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
      console.log(res);
    },
    // 提交修改请求
    edituser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          // 发起请求
          const { data: res } = await this.$axios.put(
            "users/" + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile,
            }
          );
          if (res.meta.status !== 200)
            return this.$message.error("用户修改失败");
          this.$message.success("用户修改成功");
          //添加用户框关闭
          this.editDialogVisible = false;
          this.getuserlist();
        } else {
          return false;
        }
      });
    },
    // 删除信息弹窗
    async deleteuser(id) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result != "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
      const { data: res } = await this.$axios.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户信息失败");
      }
      this.$message.success("删除用户信息成功");
      this.getuserlist();
    },
    //展示分配权限对话框
    async Assignpermissions(userinfo) {
      this.userinfo = userinfo;

      // 在展示对话框之前请求所有角色列表
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;

      this.setdialogVisible = !this.setdialogVisible;
    },
    // 点击按钮分配角色
    async saverolesinfo() {
      if (!this.selectRoleId) {
        return this.$message.error("请选择要分配的角色");
      }

      const { data: res } = await this.$axios.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectRoleId,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更新用户角色失败");
      }
      this.$message.success("更新用户角色成功");
      this.getuserlist();
      this.setdialogVisible = !this.setdialogVisible;
    },
    // 监听分配角色对话框的关闭
    setdialogclosed() {
      this.selectRoleId = "";
      this.userinfo = "";
    },
  },
};
</script>
<style lang="less" scoped>
.el-message-box {
  display: none !important;
}
</style>